<template>
  <div class="user-list-container">
    <!-- 搜索筛选区域 -->
    <el-card class="search-card" shadow="never">
      <el-form :model="searchForm" :inline="true" class="search-form">
        <el-form-item label="用户名">
          <el-input
            v-model="searchForm.username"
            placeholder="请输入用户名"
            clearable
            style="width: 200px"
          />
        </el-form-item>

        <el-form-item label="手机号">
          <el-input
            v-model="searchForm.phone"
            placeholder="请输入手机号"
            clearable
            style="width: 200px"
          />
        </el-form-item>

        <el-form-item label="邮箱">
          <el-input
            v-model="searchForm.email"
            placeholder="请输入邮箱"
            clearable
            style="width: 200px"
          />
        </el-form-item>

        <el-form-item label="状态">
          <el-select
            v-model="searchForm.status"
            placeholder="选择状态"
            clearable
            style="width: 120px"
          >
            <el-option label="全部" value="" />
            <el-option label="正常" value="active" />
            <el-option label="禁用" value="disabled" />
            <el-option label="待验证" value="pending" />
          </el-select>
        </el-form-item>

        <el-form-item label="角色">
          <el-select
            v-model="searchForm.role"
            placeholder="选择角色"
            clearable
            style="width: 120px"
          >
            <el-option label="全部" value="" />
            <el-option label="管理员" value="admin" />
            <el-option label="运营" value="operator" />
            <el-option label="普通用户" value="user" />
          </el-select>
        </el-form-item>

        <el-form-item label="注册时间">
          <el-date-picker
            v-model="searchForm.dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
            style="width: 240px"
          />
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="handleSearch">
            <IconifyIconOffline icon="ep:search" class="mr-1" />
            搜索
          </el-button>
          <el-button @click="handleReset">
            <IconifyIconOffline icon="ep:refresh" class="mr-1" />
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 操作按钮区域 -->
    <el-card class="action-card" shadow="never">
      <div class="action-bar">
        <div class="action-left">
          <el-button type="primary" @click="handleCreate">
            <IconifyIconOffline icon="ep:plus" class="mr-1" />
            新增用户
          </el-button>
          <el-button
            type="danger"
            :disabled="selectedUsers.length === 0"
            @click="handleBatchDelete"
          >
            <IconifyIconOffline icon="ep:delete" class="mr-1" />
            批量删除
          </el-button>
          <el-button type="success" @click="handleExport">
            <IconifyIconOffline icon="ep:download" class="mr-1" />
            导出数据
          </el-button>
          <el-button type="warning" @click="handleImport">
            <IconifyIconOffline icon="ep:upload" class="mr-1" />
            导入用户
          </el-button>
        </div>

        <div class="action-right">
          <el-button circle @click="handleRefresh">
            <IconifyIconOffline icon="ep:refresh" />
          </el-button>
        </div>
      </div>
    </el-card>

    <!-- 用户列表 -->
    <el-card class="table-card" shadow="never">
      <el-table
        v-loading="loading"
        :data="userList"
        stripe
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />

        <el-table-column prop="id" label="ID" width="80" />

        <el-table-column prop="avatar" label="头像" width="80">
          <template #default="{ row }">
            <el-avatar :src="row.avatar" :size="40">
              <IconifyIconOffline icon="ep:user-filled" />
            </el-avatar>
          </template>
        </el-table-column>

        <el-table-column prop="username" label="用户名" min-width="120" />

        <el-table-column prop="realName" label="真实姓名" min-width="100" />

        <el-table-column prop="phone" label="手机号" width="130" />

        <el-table-column prop="email" label="邮箱" min-width="180" />

        <el-table-column prop="role" label="角色" width="100">
          <template #default="{ row }">
            <el-tag :type="getRoleType(row.role)">
              {{ getRoleText(row.role) }}
            </el-tag>
          </template>
        </el-table-column>

        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getStatusType(row.status)">
              {{ getStatusText(row.status) }}
            </el-tag>
          </template>
        </el-table-column>

        <el-table-column prop="lastLoginTime" label="最后登录" width="160">
          <template #default="{ row }">
            <span v-if="row.lastLoginTime">{{
              formatDateTime(row.lastLoginTime)
            }}</span>
            <span v-else class="text-gray">从未登录</span>
          </template>
        </el-table-column>

        <el-table-column prop="createTime" label="注册时间" width="160">
          <template #default="{ row }">
            {{ formatDateTime(row.createTime) }}
          </template>
        </el-table-column>

        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button
              type="primary"
              link
              size="small"
              @click="handleView(row)"
            >
              查看
            </el-button>
            <el-button
              type="primary"
              link
              size="small"
              @click="handleEdit(row)"
            >
              编辑
            </el-button>
            <el-button
              type="warning"
              link
              size="small"
              @click="handleResetPassword(row)"
            >
              重置密码
            </el-button>
            <el-dropdown @command="command => handleMoreAction(command, row)">
              <el-button type="primary" link size="small">
                更多
                <IconifyIconOffline icon="ep:arrow-down" class="ml-1" />
              </el-button>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item
                    v-if="row.status === 'disabled'"
                    command="enable"
                  >
                    启用
                  </el-dropdown-item>
                  <el-dropdown-item
                    v-if="row.status === 'active'"
                    command="disable"
                  >
                    禁用
                  </el-dropdown-item>
                  <el-dropdown-item command="role"> 分配角色 </el-dropdown-item>
                  <el-dropdown-item command="delete" divided>
                    删除
                  </el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.page"
          v-model:page-size="pagination.size"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 用户详情弹窗 -->
    <el-dialog v-model="detailVisible" title="用户详情" width="600px">
      <div v-if="currentUser" class="user-detail">
        <div class="detail-header">
          <el-avatar :src="currentUser.avatar" :size="80">
            <IconifyIconOffline icon="ep:user-filled" />
          </el-avatar>
          <div class="user-info">
            <h3>{{ currentUser.realName || currentUser.username }}</h3>
            <p>{{ currentUser.email }}</p>
            <el-tag :type="getStatusType(currentUser.status)">
              {{ getStatusText(currentUser.status) }}
            </el-tag>
          </div>
        </div>

        <el-descriptions :column="2" border>
          <el-descriptions-item label="用户ID">{{
            currentUser.id
          }}</el-descriptions-item>
          <el-descriptions-item label="用户名">{{
            currentUser.username
          }}</el-descriptions-item>
          <el-descriptions-item label="真实姓名">{{
            currentUser.realName || "-"
          }}</el-descriptions-item>
          <el-descriptions-item label="手机号">{{
            currentUser.phone || "-"
          }}</el-descriptions-item>
          <el-descriptions-item label="邮箱">{{
            currentUser.email || "-"
          }}</el-descriptions-item>
          <el-descriptions-item label="角色">{{
            getRoleText(currentUser.role)
          }}</el-descriptions-item>
          <el-descriptions-item label="性别">{{
            getGenderText(currentUser.gender)
          }}</el-descriptions-item>
          <el-descriptions-item label="生日">{{
            currentUser.birthday || "-"
          }}</el-descriptions-item>
          <el-descriptions-item label="地址" :span="2">{{
            currentUser.address || "-"
          }}</el-descriptions-item>
          <el-descriptions-item label="注册时间">{{
            formatDateTime(currentUser.createTime)
          }}</el-descriptions-item>
          <el-descriptions-item label="最后登录">{{
            currentUser.lastLoginTime
              ? formatDateTime(currentUser.lastLoginTime)
              : "从未登录"
          }}</el-descriptions-item>
          <el-descriptions-item label="登录次数"
            >{{ currentUser.loginCount || 0 }}次</el-descriptions-item
          >
          <el-descriptions-item label="状态">{{
            getStatusText(currentUser.status)
          }}</el-descriptions-item>
        </el-descriptions>
      </div>
    </el-dialog>

    <!-- 分配角色弹窗 -->
    <el-dialog v-model="roleVisible" title="分配角色" width="400px">
      <el-form :model="roleForm" label-width="80px">
        <el-form-item label="用户">
          <span>{{ currentUser?.username }}</span>
        </el-form-item>
        <el-form-item label="当前角色">
          <el-tag :type="getRoleType(currentUser?.role)">
            {{ getRoleText(currentUser?.role) }}
          </el-tag>
        </el-form-item>
        <el-form-item label="新角色">
          <el-select
            v-model="roleForm.role"
            placeholder="选择角色"
            style="width: 100%"
          >
            <el-option label="管理员" value="admin" />
            <el-option label="运营" value="operator" />
            <el-option label="普通用户" value="user" />
          </el-select>
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="roleVisible = false">取消</el-button>
        <el-button type="primary" @click="handleAssignRole">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from "vue";
import { useRouter } from "vue-router";
import { ElMessage, ElMessageBox } from "element-plus";
import { IconifyIconOffline } from "@/components/ReIcon";
import dayjs from "dayjs";

const router = useRouter();

// 搜索表单
const searchForm = reactive({
  username: "",
  phone: "",
  email: "",
  status: "",
  role: "",
  dateRange: []
});

// 分页信息
const pagination = reactive({
  page: 1,
  size: 20,
  total: 0
});

// 状态
const loading = ref(false);
const selectedUsers = ref([]);
const detailVisible = ref(false);
const roleVisible = ref(false);
const currentUser = ref(null);

// 角色分配表单
const roleForm = reactive({
  role: ""
});

// 用户列表数据
const userList = ref([
  {
    id: 1,
    username: "admin",
    realName: "系统管理员",
    phone: "13800138000",
    email: "admin@example.com",
    avatar:
      "https://trae-api-sg.mchost.guru/api/ide/v1/text_to_image?prompt=professional%20avatar%20admin%20user&image_size=square",
    role: "admin",
    status: "active",
    gender: "male",
    birthday: "1990-01-01",
    address: "广东省深圳市南山区",
    lastLoginTime: "2024-01-20 10:30:00",
    loginCount: 156,
    createTime: "2023-01-01 00:00:00"
  },
  {
    id: 2,
    username: "operator01",
    realName: "运营专员",
    phone: "13800138001",
    email: "operator@example.com",
    avatar:
      "https://trae-api-sg.mchost.guru/api/ide/v1/text_to_image?prompt=professional%20avatar%20operator%20user&image_size=square",
    role: "operator",
    status: "active",
    gender: "female",
    birthday: "1992-05-15",
    address: "广东省深圳市福田区",
    lastLoginTime: "2024-01-20 09:15:00",
    loginCount: 89,
    createTime: "2023-03-15 10:00:00"
  },
  {
    id: 3,
    username: "user001",
    realName: "张三",
    phone: "13800138002",
    email: "zhangsan@example.com",
    avatar:
      "https://trae-api-sg.mchost.guru/api/ide/v1/text_to_image?prompt=casual%20avatar%20young%20man&image_size=square",
    role: "user",
    status: "active",
    gender: "male",
    birthday: "1995-08-20",
    address: "广东省广州市天河区",
    lastLoginTime: "2024-01-19 20:45:00",
    loginCount: 23,
    createTime: "2023-06-10 14:30:00"
  },
  {
    id: 4,
    username: "user002",
    realName: "李四",
    phone: "13800138003",
    email: "lisi@example.com",
    avatar:
      "https://trae-api-sg.mchost.guru/api/ide/v1/text_to_image?prompt=casual%20avatar%20young%20woman&image_size=square",
    role: "user",
    status: "disabled",
    gender: "female",
    birthday: "1993-12-03",
    address: "广东省深圳市宝安区",
    lastLoginTime: "2024-01-15 16:20:00",
    loginCount: 45,
    createTime: "2023-08-22 11:15:00"
  },
  {
    id: 5,
    username: "user003",
    realName: "王五",
    phone: "13800138004",
    email: "wangwu@example.com",
    avatar: null,
    role: "user",
    status: "pending",
    gender: "male",
    birthday: null,
    address: null,
    lastLoginTime: null,
    loginCount: 0,
    createTime: "2024-01-18 09:30:00"
  }
]);

// 格式化日期时间
const formatDateTime = (dateTime: string) => {
  return dayjs(dateTime).format("YYYY-MM-DD HH:mm");
};

// 获取角色类型
const getRoleType = (role: string) => {
  const roleMap: Record<string, string> = {
    admin: "danger",
    operator: "warning",
    user: ""
  };
  return roleMap[role] || "";
};

// 获取角色文本
const getRoleText = (role: string) => {
  const roleMap: Record<string, string> = {
    admin: "管理员",
    operator: "运营",
    user: "普通用户"
  };
  return roleMap[role] || "未知";
};

// 获取状态类型
const getStatusType = (status: string) => {
  const statusMap: Record<string, string> = {
    active: "success",
    disabled: "danger",
    pending: "warning"
  };
  return statusMap[status] || "info";
};

// 获取状态文本
const getStatusText = (status: string) => {
  const statusMap: Record<string, string> = {
    active: "正常",
    disabled: "禁用",
    pending: "待验证"
  };
  return statusMap[status] || "未知";
};

// 获取性别文本
const getGenderText = (gender: string) => {
  const genderMap: Record<string, string> = {
    male: "男",
    female: "女",
    other: "其他"
  };
  return genderMap[gender] || "未设置";
};

// 搜索
const handleSearch = () => {
  pagination.page = 1;
  loadUserList();
};

// 重置
const handleReset = () => {
  Object.assign(searchForm, {
    username: "",
    phone: "",
    email: "",
    status: "",
    role: "",
    dateRange: []
  });
  handleSearch();
};

// 新增用户
const handleCreate = () => {
  router.push("/user/create");
};

// 批量删除
const handleBatchDelete = async () => {
  try {
    await ElMessageBox.confirm(
      `确定要删除选中的 ${selectedUsers.value.length} 个用户吗？`,
      "确认删除",
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }
    );

    // 这里应该调用API批量删除用户
    ElMessage.success("删除成功");
    selectedUsers.value = [];
    loadUserList();
  } catch {
    // 用户取消
  }
};

// 导出数据
const handleExport = () => {
  // 这里应该调用导出API
  ElMessage.success("导出成功");
};

// 导入用户
const handleImport = () => {
  // 这里应该打开导入弹窗
  ElMessage.info("导入功能开发中");
};

// 刷新
const handleRefresh = () => {
  loadUserList();
};

// 选择变化
const handleSelectionChange = (selection: any[]) => {
  selectedUsers.value = selection;
};

// 查看用户
const handleView = (user: any) => {
  currentUser.value = user;
  detailVisible.value = true;
};

// 编辑用户
const handleEdit = (user: any) => {
  router.push(`/user/edit/${user.id}`);
};

// 重置密码
const handleResetPassword = async (user: any) => {
  try {
    await ElMessageBox.confirm(
      `确定要重置用户 "${user.username}" 的密码吗？`,
      "确认重置密码",
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }
    );

    // 这里应该调用API重置密码
    ElMessage.success("密码重置成功，新密码已发送到用户邮箱");
  } catch {
    // 用户取消
  }
};

// 更多操作
const handleMoreAction = async (command: string, user: any) => {
  switch (command) {
    case "enable":
      await handleStatusChange(user, "active");
      break;
    case "disable":
      await handleStatusChange(user, "disabled");
      break;
    case "role":
      currentUser.value = user;
      roleForm.role = user.role;
      roleVisible.value = true;
      break;
    case "delete":
      await handleDelete(user);
      break;
  }
};

// 状态变更
const handleStatusChange = async (user: any, status: string) => {
  const actionText = status === "active" ? "启用" : "禁用";

  try {
    await ElMessageBox.confirm(
      `确定要${actionText}用户 "${user.username}" 吗？`,
      `确认${actionText}`,
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }
    );

    // 这里应该调用API更新用户状态
    user.status = status;
    ElMessage.success(`${actionText}成功`);
  } catch {
    // 用户取消
  }
};

// 删除用户
const handleDelete = async (user: any) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除用户 "${user.username}" 吗？此操作不可恢复！`,
      "确认删除",
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }
    );

    // 这里应该调用API删除用户
    ElMessage.success("删除成功");
    loadUserList();
  } catch {
    // 用户取消
  }
};

// 分配角色
const handleAssignRole = async () => {
  if (!roleForm.role) {
    ElMessage.warning("请选择角色");
    return;
  }

  // 这里应该调用API分配角色
  currentUser.value.role = roleForm.role;
  ElMessage.success("角色分配成功");
  roleVisible.value = false;
};

// 分页大小变化
const handleSizeChange = (size: number) => {
  pagination.size = size;
  loadUserList();
};

// 当前页变化
const handleCurrentChange = (page: number) => {
  pagination.page = page;
  loadUserList();
};

// 加载用户列表
const loadUserList = async () => {
  loading.value = true;
  try {
    // 这里应该调用API获取用户列表
    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 500));
    pagination.total = 100; // 模拟总数
  } catch (error) {
    ElMessage.error("加载用户列表失败");
  } finally {
    loading.value = false;
  }
};

onMounted(() => {
  loadUserList();
});
</script>

<style scoped lang="scss">
.user-list-container {
  padding: 20px;
  background-color: #f5f7fa;
}

.search-card,
.action-card,
.table-card {
  margin-bottom: 20px;

  &:last-child {
    margin-bottom: 0;
  }
}

.search-form {
  .el-form-item {
    margin-bottom: 16px;
  }
}

.action-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;

  .action-left {
    display: flex;
    gap: 8px;
  }
}

.pagination-container {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}

.text-gray {
  color: #c0c4cc;
}

.user-detail {
  .detail-header {
    display: flex;
    align-items: center;
    gap: 20px;
    margin-bottom: 20px;
    padding-bottom: 20px;
    border-bottom: 1px solid #f0f2f5;

    .user-info {
      flex: 1;

      h3 {
        margin: 0 0 8px 0;
        font-size: 18px;
        font-weight: 600;
        color: #303133;
      }

      p {
        margin: 0 0 8px 0;
        color: #606266;
        font-size: 14px;
      }
    }
  }
}

@media (max-width: 768px) {
  .user-list-container {
    padding: 10px;
  }

  .search-form {
    .el-form-item {
      width: 100%;
      margin-bottom: 12px;

      .el-input,
      .el-select,
      .el-date-picker {
        width: 100% !important;
      }
    }
  }

  .action-bar {
    flex-direction: column;
    gap: 12px;
    align-items: stretch;

    .action-left {
      flex-wrap: wrap;
    }

    .action-right {
      align-self: flex-end;
    }
  }

  .detail-header {
    flex-direction: column;
    text-align: center;

    .user-info {
      text-align: center;
    }
  }
}
</style>
